<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="640"
    @close="handleCancel(formRef)"
  >
    <template #title>创建子网</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="resourceId"
          label="平台名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            :disabled="id"
            v-model="formData.resourceId"
            size="small"
            placeholder="请选择平台类型"
            @change="getVpcList"
          >
            <ga-option
              v-for="(item, idx) in platformTypeList"
              :key="idx"
              :label="item.type"
              :disabled="item.type !== 'huaweistack' && item.type !== 'easystack'"
              :value="item.id"
            />
          </ga-select>
        </ga-form-item>
        <ga-form-item
          field="name"
          label="子网名称"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.name" placeholder="请输入子网名称" />
        </ga-form-item>
        <ga-form-item
          field="vpcId"
          label="VPC"
          label-col-flex="70px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-select
            v-model="formData.vpcId"
            size="small"
            allow-search
            placeholder="请选择vpc"
            @change="handleChangeVpc"
          >
            <ga-option
              v-for="(item, idx) in vpcList"
              :key="idx"
              :label="item.name"
              :value="item.uuid"
            />
          </ga-select>
        </ga-form-item>
        <ga-form-item
          label-col-flex="70px"
          style="margin-bottom: 0"
          label="CIDR"
          :rules="[RULE.NOT_NULL]"
        >
          <ga-form-item
            field="ip"
            label="ip"
            hide-label
            :rules="[
              { required: true, message: '必填项不能为空' },
              { validator: validator.ip, trigger: ['change', 'input'] },
            ]"
            style="width: 200px"
          >
            <ga-input v-model="formData.ip" placeholder="请输入ip地址" />
          </ga-form-item>
          <p style="margin: 0 7px 16px">/</p>
          <ga-form-item
            hide-label
            field="cidrPart"
            label="cidrPart"
            label-col-flex="70px"
            style="width: 200px"
            :rules="[RULE.NOT_NULL]"
            :validate-trigger="['change']"
          >
            <ga-input-number
              :max="32"
              v-model="formData.cidrPart"
              placeholder="请输入掩码位"
            />
          </ga-form-item>
        </ga-form-item>
        <ga-form-item
          label-col-flex="70px"
          label="地址池"
          field="ipPools"
          :rules="[RULE.NOT_NULL]"
          :content-flex="false"
          style="margin: 0; max-height: 200px; overflow-y: auto"
        >
          <ga-form-item v-for="(item, index) in formData.ipPools" :key="index" hide-label>
            <ga-input
              v-model="item.start"
              placeholder="输入satrt地址"
              style="width: 200px"
            />
            <p style="margin: 0 7px">-</p>
            <ga-input
              v-model="item.end"
              allow-clear
              style="width: 200px; margin-right: 8px"
              placeholder="请输入end地址"
            />
            <ga-link @click="formData.ipPools.push({})" v-if="index === 0">添加</ga-link>
            <ga-link status="danger" v-else @click="formData.ipPools.splice(index, 1)"
              >删除</ga-link
            >
          </ga-form-item>
        </ga-form-item>
        <ga-form-item
          field="gatewayIp"
          label="网关"
          label-col-flex="70px"
          :rules="[
            { required: true, message: '必填项不能为空' },
            { validator: validator.ip, trigger: ['change', 'input'] },
          ]"
        >
          <ga-input v-model="formData.gatewayIp" placeholder="请输入名称" />
        </ga-form-item>
        <ga-form-item
          field="dhcpEnable"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
          label="DHCP"
          label-col-flex="70px"
        >
          <ga-switch size="mini" v-model="formData.dhcpEnable" />
        </ga-form-item>
        <ga-form-item
          field="ipv6Enable"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
          label="IPV6"
          label-col-flex="70px"
        >
          <ga-switch size="mini" v-model="formData.ipv6Enable" />
        </ga-form-item>
        <ga-form-item field="primaryDns" label="DNS1" label-col-flex="70px">
          <ga-input v-model="formData.primaryDns" placeholder="请输入DNS1" />
        </ga-form-item>
        <ga-form-item field="secondaryDns" label="DNS2" label-col-flex="70px">
          <ga-input v-model="formData.secondaryDns" placeholder="请输入DNS2" />
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk" :loading="okLoading">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
import { createNetwork } from "@/api/network";
import { getList } from "@/api/platformMgmt";
import { getNetworkList } from "@/api/network";
import { Message } from "@garco-design/web-vue";
import { RULE, validator } from "@/constant/validators";
import useLoading from "@/hooks/loading";
import { useRoute } from "vue-router";

const { loading, setLoading } = useLoading(false);
const okLoading = ref(false);
const route = useRoute();
const { id } = route.params;
const formRef = ref(null);
const formData = reactive({
  resourceId: "",
  name: "",
  vpcId: "",
  cidr: "",
  ip: "",
  cidrPart: "",
  ipPools: [{}],
  gatewayIp: "",
  dhcpEnable: true,
  ipv6Enable: true,
  primaryDns: "",
  secondaryDns: "",
});
const platformTypeList = ref([]);
const vpcList = ref([]);
// 获取平台方法
const getPlatformList = async () => {
  try {
    const { data } = await getList({ limit: -1 });
    platformTypeList.value = data.items;
  } finally {
    setLoading(false);
  }
};
// 获取vpc方法
const getVpcList = async () => {
  try {
    const { data } = await getNetworkList(
      { limit: -1, resourceId: formData.resourceId },
      "network-vpc"
    );
    vpcList.value = data.items;
  } catch (error) {
    console.log(error);
  }
};
const visible = ref(false);
const open = async () => {
  setLoading(true);
  visible.value = true;
  getPlatformList();
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    okLoading.value = true;
    try {
      const netInfo = buildNetInfo(formData);
      const { code } = await createNetwork(netInfo);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
      visible.value = false;
    } finally {
      okLoading.value = false;
    }
  }
};
// 处理buildNetInfo方法
const buildNetInfo = (formData) => {
  formData.cidr = `${formData.ip}/${formData.cidrPart}`;
  const {
    name,
    resourceId,
    vpcId,
    gatewayIp,
    cidr,
    primaryDns,
    secondaryDns,
    dhcpEnable,
    ipv6Enable,
    ipPools,
  } = formData;
  return {
    name,
    cidr,
    vpcId,
    ipv6Enable,
    dhcpEnable,
    primaryDns,
    secondaryDns,
    ipPools,
    gatewayIp,
    resourceId,
  };
};
const handleCancel = (formEl) => {
  formEl.resetFields();
  formData.ipPools = [{}];
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
